import '../lib/jquery.js'
import { $messageTip, $axios } from './util.js'

const axios = $axios()
// 主逻辑

$(document).ready(function () {
  $('button').on('click', function () {
    changeUser();
  });

  function changeUser() {
    let userInfo = sessionStorage.getItem('frontUserInfo');
    if (userInfo) {
      userInfo = JSON.parse(userInfo);
      const data = JSON.stringify({
        id: userInfo.id,
        age: $('.age').val(),
        gender: $('.gender').val(),
        nickname: $('.nickname').val(),
      });
      axios.post('/users/update', data, {
        headers: {
          'Content-Type': 'application/json'
        }
      }).then(res => {
        if (res.data) {
          const data = JSON.parse(res.data);
          $messageTip(data.message);
        }
      }).catch(err => {
        console.log(err);
      });
    }
  }

  // 获取用户信息
  function getUserInfo() {
    let userInfo = sessionStorage.getItem('frontUserInfo');
    if (userInfo) {
      userInfo = JSON.parse(userInfo);
      axios.get('/users/info', {
        params: {
          id: userInfo.id
        }
      }).then(res => {
        if (res.data) {
          const data = JSON.parse(res.data);
          if (data.code === 1) {
            $('.username').val(data.user.username);
            $('.age').val(data.user.age || '');
            $('.gender').val(data.user.gender || '');
            $('.nickname').val(data.user.nickname || '');
          } else {
            $messageTip(data.message);
          }
        }
      }).catch(err => {
        console.log(err);
      });
    } else {
      window.location.href = './index.html';
    }
  }

  // 调用 getUserInfo 函数以获取用户信息
  getUserInfo();
});


